package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmall.api.controller.ItemClient;
import com.hmall.api.controller.PayClient;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.constant.OverPayConstant;
import com.hmall.order.domain.po.Order;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class RabbitMqListener {

    private final IOrderService orderService;

    private final PayClient payClient;

    private final ItemClient itemClient;

    private final IOrderDetailService orderDetailService;

    @RabbitListener(bindings =
    @QueueBinding(
            value = @Queue(name = "pay.success.queue",durable = "true"),
            exchange =@Exchange(name = "hmall.pay",type = ExchangeTypes.DIRECT),
            key = "pay.success"
    ))
    public void listenMessage(Long orderId){
        orderService.markOrderPaySuccess(orderId);
    }

    @RabbitListener(bindings =
    @QueueBinding(
            value = @Queue(name = OverPayConstant.OVER_PAY_QUEUE,durable = "true"),
            exchange =@Exchange(name = OverPayConstant.OVER_PAY_EXCHANGE,type = ExchangeTypes.DIRECT,delayed = "true"),
            key = OverPayConstant.ROUTING_KEY
    ))
    public void listenOverTime(Long orderId){
        //查询order数据库，订单显示已支付，则return
        Order orderDB = orderService.getById(orderId);
        if(orderDB==null || orderDB.getStatus()!=1){
            return;
        }
        //查询pay client接口
        PayOrderDTO payOrder = payClient.getByOrderId(orderId);
        //如果pay数据库显示订单已支付，则同步order数据库为已支付
        if(payOrder!=null && payOrder.getStatus()==3){
            orderService.markOrderPaySuccess(orderId);
            return;
        }
        //如果pay数据库显示订单未支付，则取消订单，恢复库存
        orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getId,orderId).set(Order::getStatus,3));

        List<OrderDetailDTO> detailDTOList = orderDetailService.getItemByOrderId(orderId);
        itemClient.increaseStock(detailDTOList);
    }
}
